<template>
  <div>
    <div ref="container" class="warpper-konva-main"></div>
  </div>
</template>

<script>
import Konva from "konva";

export default {
  mounted() {
    this.initKonva();
  },
  methods: {
    initKonva() {
      const stage = new Konva.Stage({
        container: this.$refs.container,
        width: window.innerWidth,
        height: window.innerHeight,
      });

      const layer = new Konva.Layer();
      stage.add(layer);

      let isDrawing = false;
      let rect;

      stage.on("mousedown touchstart", (e) => {
        const pos = stage.getPointerPosition();
        rect = new Konva.Rect({
          x: pos.x,
          y: pos.y,
          width: 0,
          height: 0,
          stroke: "#f00",
          strokeWidth: 2,
        });

        layer.add(rect);
        isDrawing = true;
      });

      stage.on("mousemove touchmove", () => {
        if (!isDrawing) return;

        const pos = stage.getPointerPosition();
        const width = pos.x - rect.x();
        const height = pos.y - rect.y();

        rect.width(width);
        rect.height(height);
        layer.batchDraw();
      });

      stage.on("mouseup touchend", () => {
        isDrawing = false;
      });
    },
  },
};
</script>

<style scoped>
.warpper-konva-main {
  background: url("bg.jpg") no-repeat 0;
  background-size: cover;
  height: 300px;
}
/* Add your component-specific styles here */
</style>
